package com.zhugang.week01;

/**
 * @program algorithms
 * @description: palindromeStr
 * @author: chanzhugang
 * @create: 2022/05/22 16:16
 */
public class PalindromeStr2 {

    /**
     * 125.验证回文串
     *
     * @param s
     * @return
     */
    public boolean isPalindrome(String s) {
        //（前后指针）过滤非字母和数字； 忽略字母大小写
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            if (!isCharOrNum(s.charAt(i))) {
                i++;
                continue;
            }
            if (!isCharOrNum(s.charAt(j))) {
                j--;
                continue;
            }
            if (toLower(s.charAt(i)) != toLower(s.charAt(j))) {
                return false;
            } else {
                i++;
                j--;
            }
        }
        return true;
    }

    private char toLower(char c) {
        if (c >= 'a' && c <= 'z') {
            return c;
        }
        if (c >= '0' && c <= '9') {
            return c;
        }
        // 大写字母转小写
        return (char) ((int) c + 32);
    }

    private boolean isCharOrNum(char c) {
        if (c >= 'a' && c <= 'z') {
            return true;
        }
        if (c >= 'A' && c <= 'Z') {
            return true;
        }
        return c >= '0' && c <= '9';
    }


    public boolean isPalindrome2(String s) {
        // API实现： 转为小写；前后指针比较；
        String lowerCase = s.toLowerCase();
        int left = 0;
        int right = lowerCase.length() - 1;
        while (left < right) {
            // 不是字符或数字
            while (left < right && !Character.isLetterOrDigit(lowerCase.charAt(left))) {
                left++;
            }
            while (left < right && !Character.isLetterOrDigit(lowerCase.charAt(right))) {
                right--;
            }
            // 首尾字符比较
            if (lowerCase.charAt(left) != lowerCase.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

}